<?php
declare(strict_types=1);

namespace ServerApp\lib\server\tcp;

use ServerApp\lib\connection\ConfClient;
use ServerApp\lib\core\ServerType;
use ServerApp\lib\process\SProcess;
use ServerApp\lib\util\ServerHelper;

/**
 * Class AndroidPush
 * @package ServerApp\lib\server\tcp
 */
class AndroidPush
{
    private $pushTask = [];
    private $pushTaskNum = 2;

    private function createPushTask(){
        $worker_index = count($this->pushTask);
        $taskProcess = new SProcess(function() use ($worker_index){
            ConfClient::init(ServerType::SERVER, $worker_index);
            ConfClient::getInstance()->run();
//            swoole_event_add($GLOBALS['process']->pipe, [$GLOBALS['client'], 'die']);
        }, false, 2, "task_$worker_index");
        $pid = $taskProcess->start();
        $this->pushTask[$pid] = [$worker_index, $taskProcess];
    }

    private function writePid(){
        $content = implode('|', array_keys($this->pushTask));
        $s = explode('\\', __CLASS__);
        file_put_contents(ServerHelper::getInstance()->getPidPath() . end($s) . __LINE__ . ".pid", $content);
    }

    /**
     * AndroidPush constructor.
     */
    public function __construct(){
        for ($i = 0; $i < $this->pushTaskNum; $i++) {
            $this->createPushTask();
        }

        $this->writePid();

        SProcess::signal(SIGCHLD, function ($sig) {
            tracker(D, "sig:$sig");
            for(;;){
                $ret = SProcess::wait();
                if ($ret) {
                    $pid = $ret['pid'];
                    if (isset($this->pushTask[$pid])){
                        unset($this->pushTask[$pid]);
                        $this->createPushTask();
                        $this->writePid();
                    }
                }
            }
        });
    }

    private static $instance = null;

    public static function init() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
    }
}